<template>
  <view class="router-view container">
    <!-- 我要充值 -->
    <view class="container border border-bottom" v-if="type == 0">
      <view class="text-center">
        <view class="fz-20 bold">输入充值金额</view>
        <view class="uni-input m-15 bcl-white">
          <input
            type="number"
            placeholder="￥充值金额"
            v-model="postCashValue"
          />
        </view>
      </view>
    </view>

    <!-- 现在支付 -->
    <div class="container border border-bottom">
      <div class="box box-between fz-16 bold">
        <span>现在支付</span>
        <span>￥{{ workerPrice || vipPrice || postCashValue || 0 }}</span>
      </div>
      <div class="mt-10 cl-primary">价格详情</div>
    </div>

    <!-- 支付方式 -->
    <view class="pay-type text-center" v-if="type != 3">
      <view
        class="item box border border-bottom"
        style="padding: 40rpx 30rpx;"
        :class="{ active: item.id == payType }"
        v-for="(item, index) in payTypes"
        :key="index"
        @tap="changePayType(item.id)"
      >
        <view class="icon inline-block mr-10">
          <text
            class="icon icon-wechat-pay cl-success fz-36"
            v-if="item.id == 1"
          ></text>
          <text class="icon icon-ali-pay cl-primary fz-36" v-else></text>
        </view>

        <view class="mt-10">{{ item.name }}</view>
      </view>
    </view>

    <div class="container">
      <span>我同意</span>
      <span><navigator url="/user/plan?type=5">购买守则</navigator></span>
      <span>、</span>
      <span><navigator url="/user/plan?type=5">取消政策</navigator></span>
      <span>和</span>
      <span><navigator url="/user/plan?type=5">退款政策</navigator></span>
      <span>，我也同意支付以下所示的总金额（含服务费）。</span>
    </div>

    <!-- 支付按钮 -->
    <view class="container mt-40">
      <button
        class="uni-button uni-button-main uni-button-full uni-button-lg"
        :disabled="btnDisabled"
        @tap="submit"
      >
        {{
          btnDisabled
            ? "请前往小程序或者PC版进行充值"
            : `确认订单 · ￥${workerPrice || vipPrice || postCashValue || 0}`
        }}
      </button>
    </view>

    <!-- 密码输入模态框 -->
    <uni-dialog v-model="passwordDialogShow" :showBtn="false">
      <view class="text-center pl-20 pr-20 pb-20" slot="content">
        <view class="mb-20 bold fz-15">请输入支付密码</view>
        <view class="uni-input bcl-white">
          <input
            type="password"
            focus
            @submit="onPasswordDone"
            v-model="password"
          />
        </view>
        <button class="uni-button uni-button-main mt-20" @tap="onPasswordDone">
          完成
        </button>
      </view>
    </uni-dialog>

    <!-- 支付成功模态框 -->
    <uni-dialog v-model="isPaySuccess" :showBtn="false">
      <view class="text-center pl-20 pr-20 pb-20" slot="content">
        <view class="fz-15 bold">
          <text class="icon icon-success cl-main fz-30"></text>
          <text v-if="type == 0">充值成功!</text>
          <text v-else-if="type == 1">购买成功!</text>
          <text v-else-if="type == 2">支付成功!</text>
          <text v-else-if="type == 4"
            >恭喜您的雇佣请求已发送给对方，对方受理后会通知您，请耐心等待!</text
          >
          <text v-else-if="type == 5"
            >恭喜您已购买成功，请前往PC官网进行下载!</text
          >
        </view>

        <navigator open-type="navigateBack">
          <button class="uni-button uni-button-main mt-20">
            <text v-if="type == 0 || type == 1">返回</text>
            <text v-if="type == 2">前往"我的任务"查看动态</text>
            <text v-else-if="type == 4">返回店铺</text>
            <text v-else-if="type == 5">返回作品</text>
          </button>
        </navigator>
      </view>
    </uni-dialog>
  </view>
</template>

<script>
import { getConfigInfo } from "@/apis/app";
import {
  getBalance,
  bountyTaskOfWallet,
  bountyTaskOfThird,
  bountyServiceOfWallet,
  bountyServiceOfThird,
  cashPayGoods,
  thirdPayGoods,
  balanceBuyVip,
  thirdBuyVip,
  postCash,
  cashOut,
} from "@/apis/pay";
import uniDialog from "@/components/dialog";

export default {
  data() {
    return {
      btnDisabled: false,
      balance: 0, // 钱包余额
      payType: 1, // 0 钱包 1 微信 2 支付宝
      password: "",
      payTypes: [
        {
          id: 1,
          name: "微信支付",
        },
      ],

      type: 0,
      pageType: [
        "我要充值",
        "套餐支付",
        "托管赏金",
        "我要提现",
        "雇佣托管",
        "购买作品",
      ],
      passwordDialogShow: false,
      isPaySuccess: false,

      // 类型0
      postCashValue: "",

      // 类型1
      vipPrice: 0,

      // 类型2需要用的参数
      worker: "",
      workerPrice: "",
      taskId: "",

      // 类型5需要用的参数
      goodsName: "",
    };
  },

  onLoad(options) {
    // #ifdef APP-PLUS
    this.payTypes.push({
      id: 2,
      name: "支付宝支付",
    });

    if (uni.getSystemInfoSync().platform == "ios" && options.type == 0) {
      this.getConfigInfo();
    }
    // #endif

    // #ifdef H5
    this.payTypes.push({
      id: 2,
      name: "支付宝支付",
    });
    // #endif

    // 充值
    if (options.type == 0) {
      // this.payTypes.shift(0);
      // this.payType = 2;
    }

    // vip
    if (options.type == 1) {
      let { vipPrice, orderId } = options;

      this.vipPrice = vipPrice;
      this.orderId = orderId;
    }

    // 托管赏金
    if (options.type == 2) {
      let { worker, workerPrice, taskId } = options;

      this.worker = worker;
      this.workerPrice = workerPrice;
      this.taskId = taskId;
    }

    // 购买服务
    if (options.type == 4) {
      let { employId, orderId } = options;

      this.employId = employId;
      this.orderId = orderId;
    }

    // 购买作品
    if (options.type == 5) {
      let { goodsName, orderId } = options;
      this.goodsName = goodsName;
      this.orderId = orderId;
    }

    // 获取钱包余额
    this.getBalance();

    // 设置页面类型
    this.setPageType(options);
  },

  methods: {
    /**
     * 获取配置信息
     */
    async getConfigInfo() {
      let { code, data } = await getConfigInfo();
      if (code == 200) {
        this.btnDisabled = data.third_payment_method_disable == 0;
        if (this.btnDisabled) this.payTypes.length = 0;
      }
    },

    /**
     * 获取钱包余额
     */
    async getBalance() {
      let { code, data } = await getBalance();
      if (code == 200) this.balance = data.balance;
    },

    /**
     * 微信支付
     */
    async wechatPay() {
      if (this.type == 0) {
        if (!this.postCashValue) return this.$toast("请输入充值金额~");
      }

      console.log("开始支付");

      uni.showLoading({
        title: "请稍等...",
        maskL: true,
      });

      // #ifdef MP-WEIXIN
      let [err, res] = await uni.login();
      // #endif

      // #ifndef MP-WEIXIN
      let res = true;
      // #endif

      uni.hideLoading();

      if (res) {
        // #ifdef MP-WEIXIN
        let params = {
          pay_type: "xcx",
          code: res.code,
        };
        // #endif

        // #ifndef MP-WEIXIN
        let params = {
          pay_type: "wechat",
        };
        // #endif

        if (this.type == 0) {
          params.title = "余额充值";
          params.cash = this.postCashValue;
        } else if (this.type == 1) {
          // 购买vip
          params.order_code = this.orderId;
        } else if (this.type == 2) {
          params.title = "托管赏金";
          params.task_id = this.taskId;
        } else if (this.type == 4) {
          params.title = "购买服务";
          params.order_id = this.orderId;
          params.employ_id = this.employId;
        } else if (this.type == 5) {
          params.title = "购买作品";
          params.order_id = this.orderId;
        }

        let { code, data } =
          this.type == 0
            ? await postCash(params)
            : this.type == 1
            ? await thirdBuyVip(params)
            : this.type == 2
            ? await bountyTaskOfThird(params)
            : this.type == 4
            ? await bountyServiceOfThird(params)
            : await thirdPayGoods(params);

        // #ifdef MP-WEIXIN
        let payParams = {
          ...data,
          provider: "wxpay",
        };

        payParams.timeStamp = String(payParams.timeStamp);
        // #endif

        // #ifndef MP-WEIXIN
        let payParams = {
          orderInfo: data.params,
          provider: "wxpay",
        };
        // #endif

        console.log("成功获取", data);

        if (code == 200) {
          uni.showLoading({
            title: "请稍等...",
            maskL: true,
          });

          console.log("准备调用");

          let [err, res] = await uni.requestPayment(payParams);

          uni.hideLoading();

          if (res) {
            this.isPaySuccess = true;
            this.password = "";
          } else {
            console.log(err);
            this.$toast("支付失败");
          }
        } else {
          this.$toast("支付失败");
        }
      } else {
        this.$toast("支付失败");
      }
    },

    /**
     * 支付宝支付
     */
    async alipay() {
      console.log("开始支付");

      if (this.type == 0) {
        if (!this.postCashValue) return this.$toast("请输入充值金额~");
      }

      uni.showLoading({
        title: "请稍等...",
        maskL: true,
      });

      uni.hideLoading();

      let params = {
        pay_type: "alipay",
      };

      if (this.type == 0) {
        params.title = "余额充值";
        params.cash = this.postCashValue;
      } else if (this.type == 1) {
        // 购买vip
        params.order_code = this.orderId;
      } else if (this.type == 2) {
        params.title = "托管赏金";
        params.task_id = this.taskId;
      } else if (this.type == 4) {
        params.title = "购买服务";
        params.order_id = this.orderId;
        params.employ_id = this.employId;
      } else if (this.type == 5) {
        params.title = "购买作品";
        params.order_id = this.orderId;
      }

      let { code, data } =
        this.type == 0
          ? await postCash(params)
          : this.type == 1
          ? await thirdBuyVip(params)
          : this.type == 2
          ? await bountyTaskOfThird(params)
          : this.type == 4
          ? await bountyServiceOfThird(params)
          : await thirdPayGoods(params);

      let payParams = {
        orderInfo: data.payParam,
        provider: "alipay",
      };

      console.log("成功获取", data);

      if (code == 200) {
        uni.showLoading({
          title: "请稍等...",
          maskL: true,
        });

        console.log("准备调用");

        let [err, res] = await uni.requestPayment(payParams);

        console.log(err, res, 111);

        uni.hideLoading();

        if (res) {
          this.isPaySuccess = true;
          this.password = "";
        } else this.$toast("支付失败");
      } else {
        this.$toast("支付失败");
      }
    },

    /**
     * 余额支付任务托管
     */
    async bountyTaskOfWallet() {
      let params = {
        task_id: this.taskId,
        pay_type: 0,
        password: this.password,
      };

      let { code, data } = await bountyTaskOfWallet(params);

      if (code == 200) {
        this.passwordDialogShow = false;
        this.isPaySuccess = true;
        this.password = "";
      }
    },

    /**
     * 余额支付服务托管
     */
    async bountyServiceOfWallet() {
      let params = {
        order_id: this.orderId,
        employ_id: this.employId,
        pay_type: 0,
        password: this.password,
      };

      let { code, data } = await bountyServiceOfWallet(params);

      if (code == 200) {
        this.passwordDialogShow = false;
        this.isPaySuccess = true;
      }
    },

    /**
     * 余额购买作品
     */
    async cashPayGoods() {
      let params = {
        order_id: this.orderId,
        pay_type: 0,
        password: this.password,
      };

      let { code, data } = await cashPayGoods(params);

      if (code == 200) {
        this.passwordDialogShow = false;
        this.isPaySuccess = true;
        this.password = "";
      }
    },

    /**
     * 余额购买VIP
     */
    async balanceBuyVip() {
      let params = {
        order_code: this.orderId,
        password: this.password,
      };

      let { code, data } = await balanceBuyVip(params);

      if (code == 200) {
        this.passwordDialogShow = false;
        this.isPaySuccess = true;
        this.password = "";
      }
    },

    /**
     * 提现
     */
    async cashOut() {
      let params = {
        cash: this.postCashValue,
        cashout_type: "",
        alternate_password: "",
      };
    },

    changePayType(index) {
      this.payType = index;
    },

    /**
     * 确定按钮分发
     */
    submit() {
      if (this.btnDisabled) return false;

      if (this.type == 0) {
        // 充值
        if (this.payType == 1) this.wechatPay();
        else this.alipay();
      } else if (this.type == 1) {
        // vip套餐
        if (this.payType == 0) this.passwordDialogShow = true;
        else if (this.payType == 1) this.wechatPay();
        else this.alipay();
      } else if (this.type == 2) {
        // 任务托管赏金
        if (this.payType == 0) this.passwordDialogShow = true;
        else if (this.payType == 1) this.wechatPay();
        else this.alipay();
      } else if (this.type == 4) {
        // 服务托管赏金
        if (this.payType == 0) this.passwordDialogShow = true;
        else if (this.payType == 1) this.wechatPay();
        else this.alipay();
      } else if (this.type == 5) {
        // 购买作品
        if (this.payType == 0) this.passwordDialogShow = true;
        else if (this.payType == 1) this.wechatPay();
        else this.alipay();
      }
    },

    /**
     * 密码输入完毕分发
     */
    onPasswordDone() {
      if (!this.password) return this.$toast("密码不能为空~");
      if (this.type == 1) this.balanceBuyVip();
      if (this.type == 2) this.bountyTaskOfWallet();
      if (this.type == 4) this.bountyServiceOfWallet();
      if (this.type == 5) this.cashPayGoods();
    },

    /**
     * 页面类型设置
     * @params: options.type 携带 pageType 索引值对应页面类型
     */
    setPageType(options) {
      this.type = options.type;

      // 设置页面titlebar
      uni.setNavigationBarTitle({
        title: this.pageType[options.type],
      });
    },
  },

  components: {
    uniDialog,
  },
};
</script>

<style lang="scss" scoped>
.router-view {
  padding-bottom: 140upx;

  navigator {
    display: inline;
    color: $color-primary;
  }

  .pay-type {
    .item {
      background: url("/static/images/circle.png") no-repeat right center /
        60rpx;

      &.active {
        background: url("/static/images/success.png") no-repeat right center /
          60rpx;
      }
    }
  }
}
</style>
